/*
使用18B20连接到ESP01S的IO2上。开机以后会进入配网模式 连接ESP8266WIFI。浏览器输入 192.168.1.1访问配置
*/
#include "ESP8266Bafayun.h"
#include <DS18B20.h>

#define DHTPIN 2

#define USE_MQTT

#ifdef USE_MQTT
ESP8266BafayunBase *ESP8266Batayun = &ESP8266BafayunMQTT::getSingleton();
#else
ESP8266BafayunBase *ESP8266Batayun = &ESP8266BafayunTCP::getSingleton();
#endif

// 上一次上报时间
static unsigned long preUnloadMsg = millis();


float GetDS18B02Temperature() {
  static DS18B20 ds(DHTPIN);
  // 只有一个，如果多个需要while(ds.selectNext())
  return ds.getTempC();
}

volatile bool isOpen = false;

void mqtt_callback(const char *topic, const char *payload, unsigned int len) {
  String msg = payload;
  Serial.print("msg_callback:");
  Serial.println(msg);
  if (msg.startsWith("on")) {
    Serial.println("ON");
    preUnloadMsg = 0;
    isOpen = true;
  } else if (msg.startsWith("off")) {
    Serial.println("OFF");
    isOpen = false;
  }
  ESP8266Batayun->upload(isOpen?"open":"close");
}

void setup() {
  Serial.begin(115200);
  Serial.println("");
  ESP8266Batayun->setMsgCallback(std::bind(mqtt_callback, _1, _2, _3));
  ESP8266Batayun->init();
}

void loop() {
  // 检查wifi连接
  ESP8266Batayun->autoConnect();
  // 上传数据
  if (isOpen && (millis() - preUnloadMsg >= 10 * 1000)) {
    preUnloadMsg = millis();
    ESP8266Batayun->upload(String(GetDS18B02Temperature()));
  }
  ESP8266Batayun->loop();
}